//
//  PaperItemSelfRepostCell.swift
//  Exam-iOS
//
//  Created by 李胜锋 on 2018/3/19.
//  Copyright © 2018年 李胜锋. All rights reserved.
//

import Foundation
import Then
import SnapKit
import RxCocoa
import RxSwift

class PaperItemSelfRepostCell: UITableViewCell {
    
    var textField: UITextField!
    var maxScore: Double?
    var selfReportComplete:((Double)->Void)?
    var disposeBag = DisposeBag()
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setup()
        bindUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup() {
        
        self.backgroundColor = .clear
        
        let titleLabel = UILabel().then { (label) in
            label.text = "自评分:"
            label.font = UIFont.systemFont(ofSize: 14)
            
            contentView.addSubview(label)
            label.snp.makeConstraints({ (maker) in
                maker.leading.equalTo(10)
            })
        }
        
        textField = UITextField().then({ (tf) in
            tf.placeholder = "点击输入自评分"
            tf.borderStyle = .roundedRect
            tf.font = UIFont.systemFont(ofSize: 12)
            tf.keyboardType = .numberPad
            
            contentView.addSubview(tf)
            tf.snp.makeConstraints({ (maker) in
                maker.top.equalTo(10)
                maker.centerY.equalToSuperview()
                maker.centerY.equalTo(titleLabel.snp.centerY)
                maker.height.equalTo(30)
                maker.leading.equalTo(titleLabel.snp.trailing).offset(5)
            })
        })
    }
    
    private func bindUI() {
        
        textField.rx
            .controlEvent(UIControlEvents.editingDidEnd)
            .asObservable()
            .subscribe(onNext: { [weak self] in
            self?.checkInput()
        }).disposed(by: disposeBag)
    }
    
    private func checkInput() {
        if String.lsf_hasValue(textField.text) == false { return }
        let text = textField.text!
        
        ///是否是数字
        if NSPredicate.lsf_onlyNumber(text) == false {
            lsf_alert("只能输入整数")
            return
        }
        
        
        guard let score = Double(text) else { return }
        guard let maxScore = self.maxScore else { return }
        if score < 0 || score > maxScore {
            lsf_alert("只能输入0~\(maxScore)分")
            return
        }
        
        selfReportComplete?(score)
    }
    
    
}
